package org.gdstash.db;

import org.gdstash.file.ARZRecord;
import org.gdstash.util.GDMsgFormatter;
import org.gdstash.util.GDMsgLogger;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

public class DBMerchantTable {
    private static final String TABLE_NAME = "GDC_MERCHANTTABLE";
    private static final int ROW_TABLE_ID = 1;
    private String tableID;
    private List<String> itemIDs;

    public DBMerchantTable() {
        this.itemIDs = new LinkedList<String>();
    }

    private DBMerchantTable(final ARZRecord record) {
        this();
        this.tableID = record.getFileName();
        this.itemIDs = record.getMerchantTableItemIDList();
    }

    public String getMerchantTableID() {
        return this.tableID;
    }

    public List<String> getItemIDList() {
        return this.itemIDs;
    }

    public static void createTables() throws SQLException {
        final String dropTable = "DROP TABLE GDC_MERCHANTTABLE";
        final String createTable = "CREATE TABLE GDC_MERCHANTTABLE (TABLE_ID    VARCHAR(256) NOT NULL, PRIMARY KEY (TABLE_ID))";
        try (final Connection conn = GDDBData.getConnection()) {
            final boolean auto = conn.getAutoCommit();
            conn.setAutoCommit(false);
            try (final Statement st = conn.createStatement()) {
                if (GDDBUtil.tableExists(conn, "GDC_MERCHANTTABLE")) {
                    st.execute(dropTable);
                }
                st.execute(createTable);
                st.close();
                conn.commit();
            } catch (SQLException ex) {
                conn.rollback();
                final Object[] args = {"GDC_MERCHANTTABLE"};
                final String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_CREATE_TABLE", args);
                GDMsgLogger.addError(msg);
                throw ex;
            } finally {
                conn.setAutoCommit(auto);
            }
        }
        DBMerchantTableAlloc.createTable();
    }

    public static void delete(final String tableID) throws SQLException {
        final String deleteEntry = "DELETE FROM GDC_MERCHANTTABLE WHERE TABLE_ID = ?";
        try (final Connection conn = GDDBData.getConnection()) {
            final boolean auto = conn.getAutoCommit();
            conn.setAutoCommit(false);
            try (final PreparedStatement ps = conn.prepareStatement(deleteEntry)) {
                ps.setString(1, tableID);
                ps.executeUpdate();
                ps.close();
                DBMerchantTableAlloc.delete(conn, tableID);
                conn.commit();
            } catch (SQLException ex) {
                conn.rollback();
                final Object[] args = {tableID, "GDC_MERCHANTTABLE"};
                final String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_DEL_TABLE_BY_ID", args);
                GDMsgLogger.addError(msg);
                GDMsgLogger.addError(ex);
                throw ex;
            } finally {
                conn.setAutoCommit(auto);
            }
        } catch (SQLException ex2) {
            throw ex2;
        }
    }

    public static void insert(final ARZRecord record) throws SQLException {
        final DBMerchantTable entry = get(record.getFileName());
        if (entry != null) {
            return;
        }
        final DBMerchantTable merchantTable = new DBMerchantTable(record);
        if (merchantTable.itemIDs == null) {
            return;
        }
        if (merchantTable.itemIDs.isEmpty()) {
            return;
        }
        final String insert = "INSERT INTO GDC_MERCHANTTABLE VALUES (?)";
        try (final Connection conn = GDDBData.getConnection()) {
            final boolean auto = conn.getAutoCommit();
            conn.setAutoCommit(false);
            try (final PreparedStatement ps = conn.prepareStatement(insert)) {
                ps.setString(1, merchantTable.tableID);
                ps.executeUpdate();
                ps.close();
                conn.commit();
                DBMerchantTableAlloc.insert(conn, merchantTable);
            } catch (SQLException ex) {
                conn.rollback();
                final Object[] args = {record.getFileName(), "GDC_MERCHANTTABLE"};
                final String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_INS_TABLE_BY_ID", args);
                GDMsgLogger.addLowError(msg);
                GDMsgLogger.addLowError(ex);
            } finally {
                conn.setAutoCommit(auto);
            }
        }
    }

    public static DBMerchantTable get(final String tableID) {
        DBMerchantTable table = new DBMerchantTable();
        final String command = "SELECT * FROM GDC_MERCHANTTABLE WHERE TABLE_ID = ?";
        try (final Connection conn = GDDBData.getConnection();
             final PreparedStatement ps = conn.prepareStatement(command)) {
            ps.setString(1, tableID);
            try (final ResultSet rs = ps.executeQuery()) {
                final List<DBMerchantTable> list = wrap(rs);
                if (list.isEmpty()) {
                    table = null;
                } else {
                    table = list.get(0);
                }
                conn.commit();
            } catch (SQLException ex) {
                throw ex;
            }
        } catch (SQLException ex2) {
            final Object[] args = {tableID, "GDC_MERCHANTTABLE"};
            final String msg = GDMsgFormatter.format(GDMsgFormatter.rbMsg, "ERR_READ_TABLE_BY_ID", args);
            GDMsgLogger.addError(msg);
            GDMsgLogger.addError(ex2);
        }
        return table;
    }

    private static List<DBMerchantTable> wrap(final ResultSet rs) throws SQLException {
        final LinkedList<DBMerchantTable> list = new LinkedList<DBMerchantTable>();
        while (rs.next()) {
            final DBMerchantTable table = new DBMerchantTable();
            table.tableID = rs.getString(1);
            table.itemIDs = DBMerchantTableAlloc.getByMerchantTableID(table.tableID);
            list.add(table);
        }
        return list;
    }
}
